import 'dart:convert';
import 'dart:io';

import 'package:FiduMart/core/network/RequestClientMark.dart';
import 'package:FiduMart/core/network/model/association_entity.dart';
import 'package:FiduMart/core/network/model/base/base_model_entity.dart';
import 'package:FiduMart/core/network/model/currency_search_entity.dart';
import 'package:FiduMart/core/network/model/currencyrank_list_entity.dart';
import 'package:FiduMart/core/network/model/main_webcurrencyintroduct_entity.dart';
import 'package:FiduMart/core/network/model/ticker_currencytoppair_entity.dart';
import 'package:FiduMart/screen/home/QuotesController.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:r_upgrade/r_upgrade.dart';
import 'package:status_bar_control/status_bar_control.dart';
import 'package:FiduMart/core/utils/common_util.dart';
import 'package:FiduMart/core/utils/logger.dart';
import 'package:FiduMart/localization/app_export.dart';
import 'package:flutter/material.dart';
import 'package:FiduMart/screen/page1/page1_controller.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:wakelock/wakelock.dart';
import 'package:webview_flutter/webview_flutter.dart';

import '../../app_routes.dart';
import '../../constants/constants.dart';
import '../../core/utils/pref_utils.dart';

class WebController extends GetxController {
  WebViewController wvController = WebViewController();
  Rx<bool> loading = Rx(true);

  var showTitle = true.obs;

  final pref = Get.find<PrefUtils>();
  final homeController = Get.put(Page1Controller());

  List<String> urlKeywords = ['newActivity', 'myTakePartIn', 'takePartInDetail','activityExChange','/noviceMoney',];

  List<String> remoteAppUrl = ['play.google','apps.apple','t.me','reddit','twitter','facebook','instagram','youtube','tiktok'];

  final quotesController = Get.put(QuotesController());

  // late CurrencyrankListList currencyrankItemCun;
  CurrencyrankListList? currencyrankItemCun;

  var tickerCurrencytoppairEntityList = <TickerCurrencytoppairEntity>[].obs;

  var market_id = ''.obs;

  var historypriceStr = ''.obs;


  var currencySearchStr = ''.obs;
  var eurl = '';

  var miningUserStatisticstwoEntity = MainWebcurrencyintroductEntity().obs ;


  var mainWebcurrencyintroductCurrencymarketlistListList = MainWebcurrencyintroductCurrencymarketlistListList().obs ;

  var currencySearchEntity = CurrencySearchEntity().obs ;

  // late AssociationProject associationProject;
  AssociationProject? associationProject;

  static const _channel = MethodChannel('com.chain.fmart/platform');

  @override
  void onInit() {
    super.onInit();
    Wakelock.enable();
  }



  @override
  Future<void> onReady() async {
    Logger.log('webcontroller onReady');
    var homeUrl  = '';
    if(homeController.linkModels.length>0){
      // homeUrl = '${homeController.linkModels[1].link!}?cacheVersion=${DateTime.now().millisecondsSinceEpoch}';
      // homeUrl = 'https://mart.vvbit.io/#/doranswap?cacheVersion=${DateTime.now().millisecondsSinceEpoch}&source=app&isAppInstalle=${homeController.isAppInstalledD}';
      homeUrl = '${homeController.linkModels[1].link!}?cacheVersion=${DateTime.now().millisecondsSinceEpoch}&source=app&isAppInstalle=${homeController.isAppInstalledD}';
    }
    Logger.log('webcontroller onReady-homeUrl:${homeUrl}');
    eurl = Get.parameters['url'] ?? homeUrl;//'https://mart.vvbit.io/'
    String html = Get.parameters['html'] ?? '';
    String dataString = Get.parameters['data'] ?? '';
    if(dataString.isNotEmpty){
      currencyrankItemCun = CurrencyrankListList.fromJson(json.decode(dataString));
    }
    String dataAssocString = Get.parameters['assocdata'] ?? '';
    if(dataAssocString.isNotEmpty){
      associationProject = AssociationProject.fromJson(json.decode(dataAssocString));
    }
    Logger.log('eurl:${eurl}');

    wvController.clearCache();
/*    if(eurl.contains("petgarden")){
      wvController.clearCache();
    }*/

    wvController
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(const Color(0x00000000))
    // ..clearCache()
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (int progress) {
            // loading.value = false;
            Logger.log("onProgress");
            // Update loading bar.
          },
          onPageStarted: (String url) async {
            Logger.log("onPageStarted url:$url");
            //url中含有关键词时，不显示title
            if (remoteAppUrl.any((keyword) => url.contains(keyword))) {
              _launchURL(url);
              Get.offAllNamed(AppRoutes.home1);
              return;
            }
            if (urlKeywords.any((keyword) => url.contains(keyword))) {
              showTitle.value = false;
            } else {
              Logger.log("showTitle:${url}");
              showTitle.value = true;
            }
          },
          onPageFinished: (String url) async {
            loading.value = false;
            Logger.log("onPageFinished-方法已经执行.......");

            if(currencyrankItemCun!=null){
              await getWebcurrencyintroduct(currency_id:currencyrankItemCun!.currencyId.toString(),currency_on_market_id:currencyrankItemCun!.id.toString());
              await getCurrencyHistoryprice();
              await getCurrencySearch();
              getcurrencyKline(
                period: '15m',
              );
            }

            if(associationProject!=null){
              await getWebcurrencyintroduct(currency_id:associationProject!.id.toString(),currency_on_market_id:associationProject!.pairId.toString());
              await getCurrencyHistoryprice();
              await getCurrencySearch();
              getcurrencyKline(
                period: '15m',
              );
            }

            var tokenStr = await pref.getToken();
            WebViewCookieManager cookieManager =
            WebViewCookieManager(); //创建CookieManager实例
            var jsonToken = '''
            {
	"token": "${tokenStr}",
}
            ''';
            if (kReleaseMode) {
              cookieManager.setCookie(WebViewCookie(
                  name: "a",
                  value: jsonToken,
                  domain: ".umcrypto.io")); //传入要设置的Cookies列表
            } else {
              cookieManager.setCookie(WebViewCookie(
                  name: "a",
                  value: jsonToken,
                  domain: ".utonmos.com")); //传入要设置的Cookies列表
            }
          },
          onWebResourceError: (WebResourceError error) {
            Logger.log("onWebResourceError");
          },
          onNavigationRequest: (NavigationRequest request) async {
            if (request.url.startsWith('umwallet://walletconnect/authorize')) {
              await launchUrl(Uri.parse(request.url.toString()));
              return NavigationDecision.prevent;
            }
            if (request.url.startsWith('wc:')) {
              if(await isAppInstalled("com.um.wallet")){
                await launchUrl(Uri.parse("umwallet://walletconnect/authorize?param="+request.url.toString()));
              }else{
                if (GetPlatform.isAndroid) {
                  await RUpgrade.upgradeFromUrl("https://play.google.com/store/apps/details?id=com.um.wallet");
                } else if (GetPlatform.isIOS) {
                  await RUpgrade.upgradeFromAppStore("6468921385",false);
                }
              }
              return NavigationDecision.prevent;
            }
            // 否则允许打开链接
            return NavigationDecision.navigate;
          },
/*          onNavigationRequest: (NavigationRequest request) {
            return NavigationDecision.navigate;
          },*/
        ),
      )
    //window.Flutter.postMessage('bindAccount');
    //方法名bindAccount
      ..addJavaScriptChannel(
        'Flutter',
        onMessageReceived: (JavaScriptMessage message) async {
          Logger.log('Flutter---message:${message.message}');
          if (message.message == 'bindAccount') {
            bindAccount();
          } else if (message.message == 'close') {
            onBackButtonPressed();
          }else if (message.message == 'goHome') {
            CommonUtil.changePortrait();
            if (Platform.isIOS)wvController.clearCache();
            Future.delayed(Duration(milliseconds: 500),
                    () =>
                    Get.offAllNamed(AppRoutes.home1)
            );
          }else if (message.message == 'changeLandscape') {
            CommonUtil.changeLandscape();
          }else if (message.message == 'changePortrait') {
          }else if(message.message == 'nativeMining'){
            Get.back();

          }else if(message.message == 'nativeGameMore'){
            Get.back();

          }else if(message.message == 'nativeLoginDialog'){

          }else if(message.message == 'nativeNewHand'){
            Get.back();

          }else if(message.message == 'nativeRecharge'){
            Get.back();
          }else if(message.message == 'nativeInvite'){
            Get.back();

          }else if(message.message == 'goAccount'){
            Get.back();
            // Get.toNamed(AppRoutes.home4, arguments: {"type": 0});
          }
        },
      )
      ..addJavaScriptChannel("savePic", onMessageReceived: (message) {
        Logger.log('savePic---message:${message.message}');
        //截取data:image/png;base64,后面的字符串
        String prefix = "data:image/png;base64,";
        int startIndex = message.message.indexOf(prefix) + prefix.length;
        var result = message.message.substring(startIndex);
        Logger.log('savePic---result:${result}');
        saveImageToGallery(result);
      })
      ..addJavaScriptChannel("getcurrencyKline", onMessageReceived: (message) {
        Logger.log('getcurrencyKline---message:${message.message}');
        getcurrencyKline(
          // currencyrankItem:currencyrankItemCun,
          period: message.message,
        );

      });
    ;



    // ..loadRequest(Uri.parse(eurl));
    // ..loadHtmlString(eurl);
    if(eurl.isNotEmpty){
      wvController.loadRequest(Uri.parse(eurl));
    }else{
      html = processHtml(html);
      wvController.loadHtmlString(html);
    }

    super.onReady();
  }

  String processHtml(String html) {
    return html
        .replaceAll('<p', '<p style="text-align:left;font-size:60px;color:white;white-space: break-spaces;word-break: break-word;"')
        .replaceAll('<span', '<span style="text-align:left;font-size:60px;color:white;white-space: break-spaces;word-break: break-word;"')
        .replaceAll('<img', '<img style="width:90%;margin-left:5%;margin-top:2%;"')
        .replaceAll('<a', '<a style="word-wrap:break-word;display:flex;color:white;white-space: break-spaces;word-break: break-word;"')
        .replaceAll('<video', '<video style="width:100% !important;max-height:400px !important;"')
        .replaceAll('<iframe', '<iframe width="100%" height="400px"');
  }

  Future<void> onBackButtonPressed() async {
    if (await wvController.canGoBack()) {
      // 如果WebView可以返回上一级，则返回上一级
      wvController.goBack();
    } else {
      // 如果WebView不能返回上一级（即返回栈为空），则关闭页面
      CommonUtil.changePortrait();
      Future.delayed(Duration(milliseconds: 500),
              () =>
              Get.back()
      );
    }
  }

  _launchURL(String url) async {
    await launchUrl(Uri.parse(url));
  }

  @override
  void onClose() {
    super.onClose();
    Wakelock.disable();
  }

  Future<void> bindAccount() async {
    // Get.toNamed(AppRoutes.bindGame, arguments: null);
  }

  //切换横屏
  static void changeLandscape() {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.landscapeRight,
      DeviceOrientation.landscapeLeft,
    ]);
  }

  //切换竖屏
  static void changePortrait() {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);
  }

  static Future<void> saveImageToGallery(String base64String) async {
    // Check storage permission
    var status = await Permission.storage.status;
    if (!status.isGranted) {
      // Request storage permission
      status = await Permission.storage.request();
    }

    if (status.isGranted) {
      // final imageBytes = await File(imagePath).readAsBytes();
      // 将 Base64 字符串转换为 Uint8List
      Uint8List bytes = base64Decode(base64String);

      final result = await ImageGallerySaver.saveImage(bytes,name: "share${DateTime.now().millisecondsSinceEpoch}");
      if (result['isSuccess']) {
        Fluttertoast.showToast(
          msg: 'save_success'.tr,
        );
      } else {
        Fluttertoast.showToast(
          msg: 'Failed to save image',
        );
      }
    } else {
      Fluttertoast.showToast(
        msg: 'Storage permission is denied',
      );
    }
  }

  Future<void> transferGetAppData(String klineData,String details,String historyprice) async {
    Logger.log("transferGetAppData-klineData:${klineData}--details${details}");
    wvController.runJavaScript("getAppData('$klineData','$details','$historyprice');");
    // wvController.runJavaScript("getAppData('$klineData','$details');");
  }


  Future getcurrencyKline({
    // required CurrencyrankListList currencyrankItem,
    required String period,
  }) async {
    try {
      var apiName = "/currency/kline";
      // 获取当前时间
      DateTime now = DateTime.now();
      // 将当前时间转换为毫秒级时间戳
      int timestamp = now.millisecondsSinceEpoch;


      var response = await RequestClientMark().get(apiName, {
        "com_id":mainWebcurrencyintroductCurrencymarketlistListList.value.comId.toString(),
        "symbol":mainWebcurrencyintroductCurrencymarketlistListList.value.symbol.toString(),
        "anchor":'USDT',
        "market_id":mainWebcurrencyintroductCurrencymarketlistListList.value.marketId.toString(),
        "timestamp":timestamp.toString(),
        "code":CommonUtil.getEncryptCode(timestamp.toString()),
        "period":period,
        "platform":'web_pc',
        "v":'0.1.0',
        "language":'locale'.tr,
        "legal_currency":'USD'
      });

/*      var response = await RequestClientMark().get(apiName, {
        "com_id":currencyrankItem.symbol.toString().toLowerCase()+'_usdt',
        "symbol":currencyrankItem.symbol.toString(),
        "anchor":'USDT',
        "market_id":market_id.value,
        "timestamp":timestamp.toString(),
        "code":CommonUtil.getEncryptCode(timestamp.toString()),
        "period":period,
        "platform":'web_pc',
        "v":'0.1.0',
        "language":'locale'.tr,
        "legal_currency":'USD'
      });*/

      // transferGetAppData(jsonEncode(response),currencyrankItemCun.toString(),historypriceStr.value);
      transferGetAppData(jsonEncode(response),currencySearchStr.value,historypriceStr.value);

      Logger.log("data-getcurrencyKline:${response}");

    } catch (error) {
      print("Error: $error");
      throw error;
    }
  }



  Future getDataCurrenciesDetails({
    required CurrencyrankListList currencyrankItem,
  }) async {

    try {
/*      var apiName = "/ticker/currencytoppair";
      // 获取当前时间
      DateTime now = DateTime.now();
      // 将当前时间转换为毫秒级时间戳
      int timestamp = now.millisecondsSinceEpoch;

      var response = await RequestClientMark().get(apiName, {
        "currency_id":currencyrankItem.currencyId.toString(),
        "timestamp":timestamp.toString(),
        "code":CommonUtil.getEncryptCode(timestamp.toString()),
        "platform":'web_pc',
        "v":'0.1.0',
        "language":'locale'.tr,
        "legal_currency":'USD',
        "international":1,
      });

      var responseEntity =
      BaseModelEntity.fromJson(response);
      tickerCurrencytoppairEntityList.value = (responseEntity.data as List)
          .map((e) => TickerCurrencytoppairEntity.fromJson(e))
          .toList();


      Logger.log("data-数组长度：${tickerCurrencytoppairEntityList.length}");
      if(tickerCurrencytoppairEntityList!=null && tickerCurrencytoppairEntityList.length>0){
        for(int i=0;i<tickerCurrencytoppairEntityList.length;i++){
          if(
          (tickerCurrencytoppairEntityList[i].pair.toString().toLowerCase().contains('USDT'.toString().toLowerCase()))&&
              (tickerCurrencytoppairEntityList[i].marketName.toString().toLowerCase()==('Binance'.toString().toLowerCase()))
          ){
            market_id.value = tickerCurrencytoppairEntityList[i].marketId.toString();
            Logger.log("data-market_id.valueif：${market_id.value}");
            break;
          }else{
            if(tickerCurrencytoppairEntityList[i].pair.toString().toLowerCase().contains('USDT'.toString().toLowerCase())){
              market_id.value = tickerCurrencytoppairEntityList[i].marketId.toString();
              Logger.log("data-market_id.valueelse：${market_id.value}");
              break;
            }
          }
        }
      }

      if(market_id.value.toString() == "7"){
        market_id.value = "338";
      }*/


      await getWebcurrencyintroduct(currency_id:currencyrankItem.currencyId.toString(),currency_on_market_id:currencyrankItem.id.toString());

    } catch (error) {
      print("Error: $error");
      throw error;
    }

  }


  Future getCurrencyHistoryprice() async {
    try {
      var apiName = "/currency/historyprice";
      // 获取当前时间
      DateTime now = DateTime.now();
      // 将当前时间转换为毫秒级时间戳
      int timestamp = now.millisecondsSinceEpoch;

/*      var response = await RequestClientMark().get(apiName, {
        "currency_id":currencyrankItem.currencyId.toString(),
        "market_id":currencyrankItem.marketId.toString(),
        "timestamp":timestamp.toString(),
        "code":CommonUtil.getEncryptCode(timestamp.toString()),
        "platform":'web_pc',
        "v":'0.1.0',
        "language":'locale'.tr,
        "legal_currency":'USD'
      });*/

      var response = await RequestClientMark().get(apiName, {
        "currency_id":mainWebcurrencyintroductCurrencymarketlistListList.value.currencyId.toString(),
        "market_id":"",
        "timestamp":timestamp.toString(),
        "code":CommonUtil.getEncryptCode(timestamp.toString()),
        "platform":'web_pc',
        "v":'0.1.0',
        "language":'locale'.tr,
        "legal_currency":'USD'
      });


      historypriceStr.value = jsonEncode(response);

      Logger.log("data-getCurrencyHistoryprice:${historypriceStr.value}");

    } catch (error) {
      print("Error: $error");
      throw error;
    }
  }


  Future getWebcurrencyintroduct({
    required String currency_id,
    required String currency_on_market_id,
  }) async {
    try {
      var apiName = "/currency/webcurrencyintroduct";
      // 获取当前时间
      DateTime now = DateTime.now();
      // 将当前时间转换为毫秒级时间戳
      int timestamp = now.millisecondsSinceEpoch;

      var response = await RequestClientMark().get(apiName, {
        "currency_id":currency_id.toString(),
        "currency_on_market_id":currency_on_market_id.toString(),
        "timestamp":timestamp.toString(),
        "code":CommonUtil.getEncryptCode(timestamp.toString()),
        "platform":'web_pc',
        "v":'0.1.0',
        "language":'locale'.tr,
        "legal_currency":'USD'
      });


      miningUserStatisticstwoEntity.value =
      BaseModelEntity<MainWebcurrencyintroductEntity>.fromJson(response).data!;


      Logger.log("数组长度：${miningUserStatisticstwoEntity.value.currencymarketlist!.list!.list!.length}");
      if(miningUserStatisticstwoEntity.value.currencymarketlist!.list!.list!.length>0){
        mainWebcurrencyintroductCurrencymarketlistListList.value = miningUserStatisticstwoEntity.value.currencymarketlist!.list!.list![0];
        Logger.log("数组长度-marketId：${mainWebcurrencyintroductCurrencymarketlistListList.value.marketId}");
        Logger.log("数组长度-comId：${mainWebcurrencyintroductCurrencymarketlistListList.value.comId}");
      }


    } catch (error) {
      print("Error: $error");
      throw error;
    }
  }


  Future getCurrencySearch() async {
    try {
      var apiName = "/currency/search";
      // 获取当前时间
      DateTime now = DateTime.now();
      // 将当前时间转换为毫秒级时间戳
      int timestamp = now.millisecondsSinceEpoch;

      var response = await RequestClientMark().get(apiName, {
        "keyword":mainWebcurrencyintroductCurrencymarketlistListList.value.symbol.toString(),
        "timestamp":timestamp.toString(),
        "code":CommonUtil.getEncryptCode(timestamp.toString()),
        "platform":'web_pc',
        "v":'0.1.0',
        "language":'locale'.tr,
        "legal_currency":'USD'
      });


      // currencySearchStr.value = jsonEncode(response);


      // Logger.log("data-getCurrencySearch:${currencySearchStr.value}");

      currencySearchEntity.value =
      BaseModelEntity<CurrencySearchEntity>.fromJson(response).data!;

      if(currencySearchEntity.value!=null && currencySearchEntity.value.list!=null && currencySearchEntity.value.list!.length>0){
        currencySearchStr.value = currencySearchEntity.value.list![0].toString();
      }
      Logger.log("data-getCurrencySearch:${currencySearchStr.value}");


    } catch (error) {
      print("Error: $error");
      throw error;
    }
  }

  Future<bool> isAppInstalled(String packageName) async {
    // 这里添加平台特定的实现
    bool isInstalled = await _channel.invokeMethod('isAppInstalled', packageName);
    return isInstalled;
  }


}